<template>
  <div class="settlement-management">
    <!-- 操作按钮区域 -->
    <div class="operation-buttons">
      <router-link to="/orders/createOrder">
        <el-button class="mr-2" size="small" type="primary">开单</el-button>
      </router-link>
      <el-button
        type="primary"
        class="mr-2"
        size="small"
        plain
        @click="handleExport"
        :loading="exportLoading"
        :disabled="exportLoading"
      >
        导出
      </el-button>
      <el-upload
        class="mr-2"
        action="/dev-api/tms/order/import"
        :show-file-list="false"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        :before-upload="beforeImport"
      >
        <el-button type="primary" size="small" plain>导入</el-button>
      </el-upload>
      <el-button
        type="danger"
        class="mr-2"
        size="small"
        @click="cancelOrder"
        :disabled="multiple"
        plain
      >
        批量删除
      </el-button>
    </div>



    <!-- 筛选表单区域 -->
    <div class="filter-form">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-row>
          <el-col>
            <!-- 订单状态筛选 -->
            <el-form-item label="订单状态" size="small">
              <el-select v-model="filterForm.orderStatus" placeholder="请选择">
                <el-option label="全部" value=""></el-option>
                <el-option label="已开单" value="billed"></el-option>
                <el-option label="待调度" value="unSchedule"></el-option>
                <el-option label="已完成" value="completed"></el-option>
              </el-select>
            </el-form-item>

            <!-- 始发地筛选 -->
            <el-form-item label="始发地" size="small">
              <el-select v-model="filterForm.origin" placeholder="请选择">
                <el-option label="北京" value="北京"></el-option>
                <el-option label="上海" value="上海"></el-option>
                <el-option label="深圳" value="深圳"></el-option>
                <el-option label="广州" value="广州"></el-option>
              </el-select>
            </el-form-item>

            <!-- 目的地筛选 -->
            <el-form-item label="目的地" size="small">
              <el-select v-model="filterForm.destination" placeholder="请选择">
                <el-option label="北京" value="北京"></el-option>
                <el-option label="上海" value="上海"></el-option>
                <el-option label="深圳" value="深圳"></el-option>
                <el-option label="广州" value="广州"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col>
            <!-- 下单日期筛选 -->
            <el-form-item label="下单日期">
              <el-date-picker
                v-model="filterForm.createDateRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                size="small"
              ></el-date-picker>
            </el-form-item>

            <!-- 关键词搜索 -->
            <el-form-item>
              <el-input
                v-model="filterForm.keyword"
                placeholder="请输入关键词搜索"
                prefix-icon="el-icon-search"
                style="width: 200px"
                size="small"
              ></el-input>
            </el-form-item>

            <!-- 搜索和重置按钮 -->
            <el-form-item>
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button @click="handleReset" class="ml-2" size="small">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="data-table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <!-- 复选框列 -->
        <el-table-column type="selection" width="55" align="center"/>

        <!-- 订单号 -->
        <el-table-column label="订单号" width="160">
          <template slot-scope="scope">
            <router-link
              :to="{
                path: '/orders/orderInfo',
                query: {
                  orderId: scope.row.orderBasic && scope.row.orderBasic.orderId,
                }
              }"
            >
              <span style="color: #409eff; cursor: pointer;">
              {{ scope.row.orderBasic && scope.row.orderBasic.orderId || '无' }}
            </span>
            </router-link>

          </template>
        </el-table-column>

        <!-- 关联运单号 -->
        <el-table-column label="关联运单号" width="150">
          <template slot-scope="scope">
            <span>暂无数据</span>
          </template>
        </el-table-column>

        <!-- 始发地 -->
        <el-table-column label="始发地" width="100">
          <template slot-scope="scope">
            <span>{{ formatAddress(scope.row.orderBasic && scope.row.orderBasic.origin) }}</span>
          </template>
        </el-table-column>

        <!-- 目的地 -->
        <el-table-column label="目的地" width="100">
          <template slot-scope="scope">
            <span>{{ formatAddress(scope.row.orderBasic && scope.row.orderBasic.destination) }}</span>
          </template>
        </el-table-column>

        <!-- 客户名称 -->
        <el-table-column label="客户名称" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.orderBasic && scope.row.orderBasic.customerName || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 订单状态 -->
        <el-table-column label="订单状态" width="100">
          <template slot-scope="scope">
            <span :class="getOrderStatusClass((scope.row.orderBasic && scope.row.orderBasic.orderStatus) || 'billed')">
              {{ formatOrderStatus((scope.row.orderBasic && scope.row.orderBasic.orderStatus) || 'billed') }}
            </span>
          </template>
        </el-table-column>

        <!-- 发货信息 -->
        <el-table-column label="发货信息" width="180">
          <template slot-scope="scope">
            <div>联系人姓名：{{ scope.row.orderBasic && scope.row.orderBasic.senderContact || '无' }}</div>
            <div>联系电话：{{ scope.row.orderBasic && scope.row.orderBasic.senderPhone || '无' }}</div>
            <div>发货地址：{{ scope.row.orderBasic && scope.row.orderBasic.senderAddress || '无' }}</div>
          </template>
        </el-table-column>

        <!-- 收货信息 -->
        <el-table-column label="收货信息" width="180">
          <template slot-scope="scope">
            <div>联系人姓名：{{ scope.row.orderBasic && scope.row.orderBasic.receiverContact || '无' }}</div>
            <div>联系电话：{{ scope.row.orderBasic && scope.row.orderBasic.receiverPhone || '无' }}</div>
            <div>收货地址：{{ scope.row.orderBasic && scope.row.orderBasic.receiverAddress || '无' }}</div>
          </template>
        </el-table-column>

        <!-- 预计发货时间 -->
        <el-table-column label="预计发货时间" width="140">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.orderBasic && scope.row.orderBasic.planSendTime) }}</span>
          </template>
        </el-table-column>

        <!-- 预计收货时间 -->
        <el-table-column label="预计收货时间" width="140">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.orderBasic && scope.row.orderBasic.planReceiveTime) }}</span>
          </template>
        </el-table-column>

        <!-- 订单类型 -->
        <el-table-column label="运输类型" width="100">
          <template slot-scope="scope">
            <span>{{ formatTransportType(scope.row.orderBasic && scope.row.orderBasic.transportType) }}</span>
          </template>
        </el-table-column>

        <!-- 货物类型 -->
        <el-table-column label="货物类型" width="100">
          <template slot-scope="scope">
            <span>{{ formatGoodsType(scope.row.orderBasic && scope.row.orderBasic.goodsType) }}</span>
          </template>
        </el-table-column>

        <!-- 货物数量 -->
        <el-table-column label="货物数量" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsList && scope.row.goodsList.length > 0">
              {{
                scope.row.goodsList.reduce((total, item) => {
                  return total + Number(item.quantity || 0);
                }, 0)
              }}
            </span>
            <span v-else style="color: #909399;">无</span>
          </template>
        </el-table-column>

        <!-- 总体积 -->
        <el-table-column label="总体积(m³)" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsList && scope.row.goodsList.length > 0">
              {{ calcTotalVolume(scope.row.goodsList).toFixed(1) }}
            </span>
            <span v-else>0.0</span>
          </template>
        </el-table-column>

        <!-- 总重量 -->
        <el-table-column label="总重量(kg)" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsList && scope.row.goodsList.length > 0">
              {{ calcTotalWeight(scope.row.goodsList).toFixed(1) }}
            </span>
            <span v-else>0.0</span>
          </template>
        </el-table-column>

        <!-- 运费合计 -->
        <el-table-column label="运费合计" width="100">
          <template slot-scope="scope">
            <span>¥{{
                (scope.row.costInfo && scope.row.costInfo.totalCost ? scope.row.costInfo.totalCost.toFixed(2) : '0.00')
              }}</span>
          </template>
        </el-table-column>

        <!-- 订单来源 -->
        <el-table-column label="订单来源" width="100">
          <template slot-scope="scope">
            <span>{{ formatOrderSource(scope.row.orderBasic && scope.row.orderBasic.orderSource) }}</span>
          </template>
        </el-table-column>

        <!-- 订单备注 -->
        <el-table-column label="订单备注" min-width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.orderRemark && scope.row.orderRemark.remark || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 下单时间 -->
        <el-table-column label="下单时间" width="140">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.orderBasic && scope.row.orderBasic.orderTime) }}</span>
          </template>
        </el-table-column>

        <!-- 创建人 -->
        <el-table-column label="创建人" width="100">
          <template slot-scope="scope">
            <span>未知</span>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column label="创建时间" width="140">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.orderBasic && scope.row.orderBasic.createTime) || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!--            <el-button type="text" @click="goDispatch(scope.row)">调度</el-button>-->
            <router-link
              :to="{
                path: '/orders/orderInfo',
                query: {
                  orderId: scope.row.orderBasic && scope.row.orderBasic.orderId,
                  orderBasic: scope.row.orderBasic,
                  goodsList: scope.row.goodsList,
                  costInfo: scope.row.costInfo,
                  orderRemark: scope.row.orderRemark,
                  paymentMethod: scope.row.paymentMethod,
                  vehicleRequirement: scope.row.vehicleRequirement,
                }
              }"
            >
              <el-button type="text">详情</el-button>
            </router-link>
            <el-button type="text" @click="cancelOrder(scope.row)" style="color: #f56c6c;">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        v-show="total > 0"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script>
import {cancelOrder, listOrderInfo} from "@/api/tms/orders/order";
import {getToken} from '@/utils/auth';
import axios from "axios";

export default {
  name: 'SettlementManagement',
  data() {
    return {
      // 批量操作相关状态
      multiple: true,       // 无选中项时为true（控制按钮禁用）
      orderIds: [],         // 选中的订单ID列表
      selectedOrders: [],   // 选中的完整订单数据

      // 筛选表单数据
      filterForm: {
        orderStatus: '',
        origin: '',
        destination: '',
        createDateRange: [],
        keyword: ''
      },

      // 表格数据
      tableData: [],
      total: 0,

      // 分页参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },

      // 加载状态
      loading: false,
      exportLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 处理复选框选中事件 - 核心：收集选中订单ID
     */
    handleSelectionChange(selection) {
      this.selectedOrders = selection;
      // 提取选中订单的orderId（处理可能的null值）
      this.orderIds = selection
        .map(item => item.orderBasic?.orderId)  // 使用可选链避免null报错
        .filter(id => id);                     // 过滤无效ID

      // 更新批量操作按钮状态（无选中则禁用）
      this.multiple = this.orderIds.length === 0;
      console.log("选中的订单ID列表：", this.orderIds);
    },

    /**
     * 获取订单列表数据
     */
    getList() {
      this.loading = true;
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        keyword: this.filterForm.keyword,
        orderStatus: this.filterForm.orderStatus,
        origin: this.filterForm.origin,
        destination: this.filterForm.destination
      };

      // 处理日期范围
      if (this.filterForm.createDateRange && this.filterForm.createDateRange.length === 2) {
        params.beginCreateTime = this.filterForm.createDateRange[0];
        params.endCreateTime = this.filterForm.createDateRange[1];
      }

      // 调用接口获取数据
      listOrderInfo(params)
        .then(response => {
          this.tableData = response.data || [];
          this.total = this.tableData.length;
          this.loading = false;
        })
        .catch(error => {
          console.error('获取数据失败:', error);
          this.$message.error('获取数据失败');
          this.tableData = [];
          this.total = 0;
          this.loading = false;
        });
    },

    /**
     * 搜索处理
     */
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 重置筛选条件
     */
    handleReset() {
      this.filterForm = {
        orderStatus: '',
        origin: '',
        destination: '',
        createDateRange: [],
        keyword: ''
      };
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      };
      this.getList();
    },

    /**
     * 分页大小改变
     */
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 当前页改变
     */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    /**
     * 格式化订单状态显示
     */
    formatOrderStatus(status) {
      const statusMap = {
        'unbilled': '未开单',
        'billed': '已开单',
        'partiallyBilled': '部分开单'
      };
      return statusMap[status] || '未知状态';
    },

    /**
     * 获取订单状态样式类
     */
    getOrderStatusClass(status) {
      const classMap = {
        'unbilled': 'status-unbilled',
        'billed': 'status-billed',
        'partiallyBilled': 'status-partially'
      };
      return classMap[status] || 'status-unknown';
    },

    /**
     * 格式化地址（英文转中文）
     */
    formatAddress(addressCode) {
      const addressMap = {
        'beijing': '北京',
        'shanghai': '上海',
        'shenzhen': '深圳',
        'guangzhou': '广州'
      };
      return addressMap[addressCode] || addressCode || '无';
    },

    /**
     * 格式化货物类型
     */
    formatGoodsType(goodsTypeCode) {
      const goodsTypeMap = {
        'electronics': '电子产品',
        'clothing': '服装',
        'food': '食品'
      };
      return goodsTypeMap[goodsTypeCode] || goodsTypeCode || '无';
    },

    /**
     * 格式化运输类型
     */
    formatTransportType(transportTypeCode) {
      const transportTypeMap = {
        'road': '公路',
        'rail': '铁路',
        'air': '航空'
      };
      return transportTypeMap[transportTypeCode] || transportTypeCode || '无';
    },

    /**
     * 格式化订单来源
     */
    formatOrderSource(sourceCode) {
      const sourceMap = {
        'online': '线上',
        'offline': '线下',
        'app': 'APP'
      };
      return sourceMap[sourceCode] || sourceCode || '无';
    },

    /**
     * 格式化日期显示
     */
    formatDate(dateStr) {
      if (!dateStr) return '无';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-');
    },

    /**
     * 计算总体积
     */
    calcTotalVolume(goodsList) {
      return goodsList.reduce((total, item) => total + (item.volume || 0), 0);
    },

    /**
     * 计算总重量
     */
    calcTotalWeight(goodsList) {
      return goodsList.reduce((total, item) => total + (item.weight || 0), 0);
    },

    /**
     * 跳转到调度页面
     */
    goDispatch(row) {
      this.$router.push({
        path: '/dispatch',
        query: {orderNo: row.orderBasic?.orderId}
      });
    },

    /**
     * 取消订单
     */
    cancelOrder(row) {
      const orderIds = row ? [row.orderBasic?.orderId].filter(id => id) : this.orderIds;
      if (orderIds.length === 0) {
        this.$message.warning('请选择需要取消的订单');
        return;
      }

      this.$modal.confirm(`确定要取消选中的 ${orderIds.length} 条订单吗?`)
        .then(() => cancelOrder(orderIds))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("订单取消成功");
        })
        .catch(() => {
        });
    },

    /**
     * 处理导出 - 核心：支持选中导出和筛选导出
     */
    handleExport() {
      // 验证：无选中且无筛选条件时提示
      if (this.orderIds.length === 0 &&
        !this.filterForm.keyword &&
        !this.filterForm.orderStatus &&
        !this.filterForm.origin &&
        !this.filterForm.destination &&
        !this.filterForm.createDateRange.length) {
        this.$message.warning('请选择订单或设置筛选条件后导出');
        return;
      }

      this.exportLoading = true;
      const params = new URLSearchParams();

      // 1. 优先导出选中订单（若有选中）
      if (this.orderIds.length > 0) {
        this.orderIds.forEach(id => params.append('orderIds', id));
        this.$message.info(`正在导出选中的 ${this.orderIds.length} 条订单...`);
      }
      // 2. 无选中时按筛选条件导出
      else {
        params.append('keyword', this.filterForm.keyword || '');
        params.append('orderStatus', this.filterForm.orderStatus || '');
        params.append('origin', this.filterForm.origin || '');
        params.append('destination', this.filterForm.destination || '');

        if (this.filterForm.createDateRange && this.filterForm.createDateRange.length === 2) {
          params.append('beginCreateTime', this.filterForm.createDateRange[0]);
          params.append('endCreateTime', this.filterForm.createDateRange[1]);
        }
      }

      // 发送导出请求
      axios({
        url: `/dev-api/tms/order/export?${params.toString()}`,
        method: 'get',
        responseType: 'blob', // 关键：指定接收二进制文件流
        headers: {
          'Authorization': 'Bearer ' + getToken()
        }
      }).then(response => {
        // 处理文件下载
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        // 获取文件名（优先从响应头获取，否则自定义）
        let fileName = '订单数据.xlsx';
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
          fileName = decodeURIComponent(contentDisposition.split('filename=')[1]);
        } else {
          fileName = `订单数据_${new Date().toLocaleDateString()}.xlsx`;
        }

        // 创建下载链接并触发下载
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        link.click();

        // 释放资源
        window.URL.revokeObjectURL(url);
        this.exportLoading = false;
        this.$message.success('导出成功！');
      }).catch(error => {
        console.error('导出失败:', error);
        this.exportLoading = false;
        this.$message.error('导出失败，请重试');
      });
    },

    /**
     * 导入前验证
     */
    beforeImport(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('请上传Excel文件！');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB！');
        return false;
      }

      return true;
    },

    /**
     * 导入成功处理
     */
    handleImportSuccess(response) {
      this.$message.success(response.data || '导入成功');
      this.getList();
    },

    /**
     * 导入失败处理
     */
    handleImportError(error) {
      console.error('导入失败:', error);
      this.$message.error('导入失败：' + (error.response?.data?.message || '未知错误'));
    }
  }
};
</script>

<style scoped>
.settlement-management {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.operation-buttons {
  margin-bottom: 20px;
}

.filter-form {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.data-table {
  margin-top: 10px;
}

.mr-2 {
  margin-right: 8px !important;
}

.ml-2 {
  margin-left: 8px !important;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

/* 订单状态样式 */
.status-unbilled {
  color: #e6a23c;
  font-weight: bold;
}

.status-billed {
  color: #67c23a;
  font-weight: bold;
}

.status-partially {
  color: #409eff;
  font-weight: bold;
}

.status-unknown {
  color: #909399;
  font-weight: bold;
}

/* 表格内容样式优化 */
::v-deep .el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.operation-buttons {
  /* 使用Flex布局让子元素在同一行显示 */
  display: flex;
  /* 垂直居中对齐 */
  align-items: center;
  /* 按钮之间的间距 */
  gap: 8px;
  /* 底部外边距，与下方内容分隔 */
  margin-bottom: 20px;
  /* 允许在小屏幕上自动换行 */
  flex-wrap: wrap;
}

/* 移除Element UI按钮默认的margin，避免与gap冲突 */
.operation-buttons >>> .el-button {
  margin: 0 !important;
}
</style>
